<script setup>
import { ref, computed, watch, onMounted, nextTick } from 'vue'
import { dataAPI } from '@/services/api'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import ExperimentSelector from '@/components/ExperimentSelector.vue'
import { useExperimentStore } from '@/stores/experiment'

const loading = ref(false)
const dataList = ref({ tables: [] })
const activeTableName = ref('')

const queryParams = ref({
  experimentId: '',
  startTime: '',
  endTime: '',
  page: 1,
  pageSize: 100,
  tableName: ''
})

const experimentStore = useExperimentStore()

// 获取当前选中的表格及其分页信息
const currentTable = computed(() => {
  if (!dataList.value?.tables) return null
  return dataList.value.tables.find(t => t.table_name === activeTableName.value)
})

const fetchData = async () => {
  loading.value = true
  try {
    const response = await dataAPI.getData(queryParams.value)
    dataList.value = response.data
  } catch (error) {
    console.error('Error fetching data:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 处理页码改变
const handleCurrentChange = async (page) => {
  queryParams.value.page = page
  // 保存当前选中的表格名称
  const currentTab = activeTableName.value
  await handleQuery()
  // 查询完成后恢复选中的表格
  nextTick(() => {
    activeTableName.value = currentTab
  })
}

// 处理每页条数改变
const handleSizeChange = async (size) => {
  queryParams.value.pageSize = size
  queryParams.value.page = 1
  // 保存当前选中的表格名称
  const currentTab = activeTableName.value
  await handleQuery()
  // 查询完成后恢复选中的表格
  nextTick(() => {
    activeTableName.value = currentTab
  })
}

// 当获取到数据后，更新查询参数
watch(() => dataList.value, (newData) => {
  if (newData) {
    queryParams.value = {
      ...queryParams.value,
      experimentId: newData.experiment_id,
      startTime: newData.actual_start_time,
      endTime: newData.actual_end_time
    }
  }
}, { immediate: true })

// 当数据加载完成后，设置默认选中的 tab
watch(() => dataList.value?.tables, (newTables) => {
  if (newTables?.length > 0) {
    activeTableName.value = newTables[0].table_name
  }
}, { immediate: true })

// 获取当前选中表的数据
const currentTableData = computed(() => {
  if (!dataList.value?.tables) return []
  const table = dataList.value.tables.find(t => t.table_name === activeTableName.value)
  return table?.data || []
})

// 修改列定义，优化时间显示
const columns = computed(() => {
  const currentTable = dataList.value?.tables?.find(t => t.table_name === activeTab.value)
  if (!currentTable?.data?.length || !currentTable?.columns) return []
  
  return [
    { 
      prop: '0', 
      label: currentTable.columns[0] || '时间',
      width: 180,
      formatter: (row) => row[0]
    },
    ...Array.from({ length: currentTable.columns.length - 1 }, (_, i) => ({
      prop: String(i + 1),
      label: currentTable.columns[i + 1],
      formatter: (row) => {
        const value = row[i + 1]
        return value !== null && value !== undefined ? value : '-'
      }
    }))
  ]
})


// 计算表格高度
const tableHeight = computed(() => {
  return 'calc(100vh - 260px)'  // 调整这个值以适应你的布局
})

// 查询数据
const handleQuery = async () => {
  if (!queryParams.value.experimentId) {
    ElMessage.warning('请选择实验ID')
    return
  }
  loading.value = true
  try {
    const response = await dataAPI.getData(queryParams.value)
    dataList.value = response.data
    // 只在首次加载时设置默认表格
    if (!activeTableName.value && response.data.tables?.length > 0) {
      activeTableName.value = response.data.tables[0].table_name
    }
  } catch (error) {
    console.error('Error fetching data:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  const experimentId = experimentStore.getCurrentExperiment()
  if (experimentId) {
    queryParams.value.experimentId = experimentId
  } else {
    queryParams.value.experimentId = null
  }
  fetchData()
})


</script>

<template>
  <div class="data-view">
    <!-- 查询表单 -->
    <el-form :model="queryParams" inline class="search-form">
      <el-form-item label="实验ID">
        <ExperimentSelector 
          v-model="queryParams.experimentId" 
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="开始时间">
        <el-date-picker
          v-model="queryParams.startTime"
          type="datetime"
          placeholder="开始时间"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="X"
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="结束时间">
        <el-date-picker
          v-model="queryParams.endTime"
          type="datetime"
          placeholder="结束时间"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="X"
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格选择器 -->
    <el-tabs 
      v-model="activeTableName" 
      @tab-change="handleTableChange"
      v-if="dataList.tables?.length"
    >
      <el-tab-pane
        v-for="table in dataList.tables"
        :key="table.table_name"
        :label="table.table_name"
        :name="table.table_name"
      >
        <el-table
          v-loading="loading"
          :data="table.data"
          :height="tableHeight"
          style="width: 100%"
          border
        >
          <el-table-column
            v-for="(column, index) in table.columns"
            :key="column"
            :label="column"
            :min-width="index === 0 ? 180 : 120"
          >
            <template #default="{ row }">
              {{ row[index] }}
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页器 -->
        <div class="pagination-container" v-if="table.pagination">
          <el-pagination
            v-model:current-page="table.pagination.current_page"
            v-model:page-size="table.pagination.page_size"
            :page-sizes="[50, 100, 200, 500]"
            :total="table.pagination.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            layout="total, sizes, prev, pager, next"
            background
          />
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<style scoped>
.data-view {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.table-container {
  flex: 1;
  min-height: 0;  /* 允许flex子项收缩 */
}

.mt-4 {
  margin-top: 16px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 表格内容紧凑一些 */
:deep(.el-table td) {
  padding: 4px 0;
}

.search-form {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.search-form :deep(.el-form-item) {
  margin-bottom: 0;
  margin-right: 16px;
}

.search-form :deep(.el-form-item:last-child) {
  margin-right: 0;
}
</style>